package bsc.war.form;

import bsc.ejb.metadata.License;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.service.BSCUtils;
import java.util.Calendar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author memozac
 */
public class NewLicense  extends AbstractController  {

     @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
         HttpServletResponse response) throws Exception {
        DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");

        try {
            License currentLicense = delegate.findCurrentLicense();
            
            String _license = request.getParameter("license");
            String currentToken = request.getParameter("currentToken");
            String newToken = request.getParameter("newToken");
            
            BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
            textEncryptor.setPassword(BSCUtils.ENCRYPT_HASH_KEY);
            if(currentLicense == null){
                License license = (License) Factory.getBean("License");

                license.setLicense(textEncryptor.encrypt(_license));
                license.setToken(textEncryptor.encrypt(newToken));
                license.setLicenseDate(Calendar.getInstance().getTime());

                delegate.createLicense(license);
            } else {
                if(currentToken != null && textEncryptor.decrypt(currentLicense.getToken()).equals(currentToken)) {
                    License license = (License) Factory.getBean("License");

                    license.setLicense(textEncryptor.encrypt(_license));
                    license.setToken(textEncryptor.encrypt(newToken));
                    license.setLicenseDate(Calendar.getInstance().getTime());

                    delegate.createLicense(license);
                } else {
                    request.setAttribute("errorToken", true);
                }
            }
            
        } catch (Exception e) {e.printStackTrace();}

        return  new ModelAndView("newLicense");
    }

}
